/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lin.cms.logging;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Method invocation interceptor.
 * 
 * @author Byeongkil Woo
 */
public class MethodInvocationInfoInterceptor implements HandlerInterceptor {

	private static final Log logger = LogFactory.getLog(MethodInvocationInfoInterceptor.class);
	
	public static final ThreadLocal<List<String>> MESSAGE_LIST_CONTEXT = new ThreadLocal<List<String>>() {
		@Override
		protected List<String> initialValue() {
			return new ArrayList<String>();
		}
	};
	
	public static final ThreadLocal<Integer> METHOD_DEPTH_CONTEXT = new ThreadLocal<Integer>() {
		@Override
		protected Integer initialValue() {
			return new Integer(0);
		}
	};
	
	public static void addMessage(String message) {
		MESSAGE_LIST_CONTEXT.get().add(message);
	}
	
	public static void increaseDepth() {
		addDepth(1);
	}
	
	public static void decreaseDepth() {
		addDepth(-1);
	}
	
	private static void addDepth(int amount) {
		Integer depth = (Integer) METHOD_DEPTH_CONTEXT.get();
		METHOD_DEPTH_CONTEXT.set(new Integer(depth.intValue() + amount));
	}
	
	public static int getCurrentDepth() {
		return ((Integer) METHOD_DEPTH_CONTEXT.get()).intValue();
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		addMessage("URI: " + request.getRequestURI());		
		addMessage("Handler: " + handler);

		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		addMessage(modelAndView.toString());
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		if (logger.isDebugEnabled()) {
			StringBuffer buffer = new StringBuffer();
			buffer.append(Thread.currentThread());
			buffer.append("\n------------------------------------------------------------------------\n");
			buffer.append(StringUtils.collectionToDelimitedString(MESSAGE_LIST_CONTEXT.get(), "\n"));
			buffer.append("\n------------------------------------------------------------------------");
			
			logger.debug(buffer.toString());
		}
		
		MESSAGE_LIST_CONTEXT.get().clear();
		METHOD_DEPTH_CONTEXT.set(new Integer(0));
	}

}
